using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;

namespace FeatureActivateMasterPage.Features.Feature1
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("5c4afbff-9a5b-46e6-82dc-39329f25fcd0")]
    public class Feature1EventReceiver : SPFeatureReceiver
    {
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            // Get the SPWeb we're being activated in.
            var web = (SPWeb)properties.Feature.Parent;

            if (null != web)
            {
                // Get the Site Collection root path to get the master page gallery.
                string siteCollectionRoot = web.Site.RootWeb.Url;

                // Set the Site Master to Custom.master
                var siteMaster = new Uri(siteCollectionRoot +
                                         "/_catalogs/masterpage/" +
                                         "v5.Master");
                web.CustomMasterUrl = siteMaster.AbsolutePath;

                // Set the System Master to Custom.master
                var systemMaster = new Uri(siteCollectionRoot +
                                           "/_catalogs/masterpage/" +
                                           "v5.Master");
                web.MasterUrl = systemMaster.AbsolutePath;

                // Clear the Alternate CSS
                web.AlternateCssUrl = string.Empty;

                // Save the changes back to the web
                web.Update();
            }
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            // Get the SPWeb we're being activated in.
            var web = (SPWeb)properties.Feature.Parent;

            if (null != web)
            {
                // Get the Site Collection root path to get the master page gallery.
                string siteCollectionRoot = web.Site.RootWeb.Url;

                // Set both Master Pages to v4.master
                var siteMaster = new Uri(siteCollectionRoot +
                                         "/_catalogs/masterpage/" +
                                         "v4.master");
                web.CustomMasterUrl = siteMaster.AbsolutePath;
                web.MasterUrl = siteMaster.AbsolutePath;

                // Clear the Alternate CSS
                web.AlternateCssUrl = string.Empty;

                // Save the changes back to the web
                web.Update();
            }
        }
    }
}
